/**
 * Copyright (C) 2007 The AsyncMail Group <asyncmail@googlegroups.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.asyncmail.smtpserver.mina.filter;

import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.logging.Log;
import org.apache.mina.common.IoFilterAdapter;
import org.apache.mina.common.IoSession;
import org.springframework.beans.factory.annotation.Required;

/**
 * This filter delay the greeting for the given delay time. Delaying of the
 * greeting seems to be a good technic again spambots
 * 
 */
public class GreetDelayFilter extends IoFilterAdapter {

    private Log logger;

    private long greetDelayTime = 20;

    @Required
    public void setLogger(Log logger) {
        this.logger = logger;
    }

    public void setGreetDelayTime(long greetDelayTime) {
        this.greetDelayTime = greetDelayTime;
    }

    @Override
    public void sessionCreated(NextFilter arg0, IoSession arg1)
            throws Exception {
        logger.debug("Delay greeting for " + greetDelayTime + " ms");
        new Timer().schedule(new GreetDelayTask(arg0, arg1), greetDelayTime);
    }

    private class GreetDelayTask extends TimerTask {

        private NextFilter filter;

        private IoSession session;

        public GreetDelayTask(NextFilter filter, IoSession session) {
            this.filter = filter;
            this.session = session;
        }

        @Override
        public void run() {
            filter.sessionCreated(session);
        }

    }

}
